/**map下拉、左右图表*/
define(["echarts",'page','liMarquee','select2'],function (echarts,page,liMarquee,select2){
    return {
        init:function(){
            var that = this;
            that.mapEchart();
            that.Selectcity();
        },
    	mapEchart:function(){
           setTimeout(resizePie(),5000);
           $(window).resize(function(){resizePie();});
           var dataLeft = $('.dataLeft'),dataRight = $('.dataRight');
           $(".collect").on('click',function(){
                if($(this).children().hasClass('fa-backward')){
                    dataLeft.addClass('slideOutLeft').removeClass('slideInLeft');
                    $(this).css("left","0px").children().removeClass('fa-backward').addClass('fa-forward');
                }else{
                    dataLeft.addClass('slideInLeft').removeClass('slideOutLeft');
                    $(this).css("left","280px").children().removeClass('fa-forward').addClass('fa-backward');
                }
           });
           $(".shrink").on('click',function(){
               if($(this).children().hasClass('fa-forward')){
                   dataRight.removeClass('slideInRight').addClass('slideOutRight');
                   $(this).css("right","0").children().removeClass('fa-forward').addClass('fa-backward');
                   $('.draw-open,.zoom').css({right:'20px'});
               }else{
                   dataRight.removeClass('slideOutRight').addClass('slideInRight');
                   $(this).css("right","280px").children().removeClass('fa-backward').addClass('fa-forward');
                   $('.draw-open,.zoom').css({right:'310px'});
               }
           });
    	},
        Selectcity:function () {
            $('.select-item').select2({minimumResultsForSearch:-1});
            var city = $("select[name='city']");
            var county = $("select[name='county']");
            var sb = new StringBuffer();
            $.ajax({
                url: "/positionAreaController/getAreaTree",
                dataType: "json",
                type: "post",
                success:function (result) {
                    if(result.code==10001){
                        var cityJson = result.data;
                        $.each(cityJson,function(i, val) {
                            sb.append("<option value='"+val.name+"'>" + val.name + "</option>");
                        });
                        city.append(sb.toString());
                        city.on('change',function () {doCityAndCountyRelation(cityJson,city,county)});
                        city.select2({minimumResultsForSearch: -1});
                    }
                }
            });
        },
        getSelectVal:function ($dom) {
            if($dom.select2('val')=='全部'){
                return '';
            }else{
                return $dom.select2('val');
            }
        }
    };
    //图表适配
    function resizePie(){
        $('.data').show();
        var height=(($(window).height()-$(".map-name").height()-$(".map-info").height()-24)/3).toFixed(0);
        $(".personDistribution,.attentionTime,.jurisdictionManage,.alarmDistribution").css({"height":(height-48)+"px"});
        getJurisdictionManageData();//在辖区占比
        getPersonDistributionData();//人员分布
        getAttentionTimeData()//关注时间
        getAlarmTypeData();//告警类型
        getalarmTable();//实时告警
    }
    //时间格式处理
    function timeFormatter(time){
        var reg = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/;
        return (time.replace(reg, '$1-$2-$3'+"<br/>"+'$4:$5'));
    }
    //分页插件
    function pagenation(total) {
        $('#page').empty();
        pageUtil.initPage('page',{
            totalCount:total,
            curPage:1,
            showCount:3,
            defaultPageSize:5,
            isJump:true,
            isPageNum:false,
            //isPN:true,
            isFL:false,
            jump: function (curPage, pageSize) {
                $.ajax({
                    url:"/alarmLogController/pageSelect",
                    type:"post",
                    data:{page:curPage, rows:5},
                    dataType:"json",
                    success:function(result){
                        if(result.rows.length>0){
                            var html="";
                            for(var i in result.rows){
                                html+="<tr><td>"+timeFormatter(result.rows[i].alarmTime)+"</td><td>"+result.rows[i].userPhone+"</td><td>"+result.rows[i].alarmName.replace(/告警/,"")+"</td><td><p class='alarm-content'>"+result.rows[i].alarmContent+"</p></td></tr>"
                            }
                            $("#alarmContent").empty().html(html);
                            $(".alarm-content").liMarquee({direction: 'left',circular:true,scrolldelay:0,scrollamount:30,isEqual:true,runshort: false});
                        }
                    }
                })
            }
        });
        $(".alarm-content").liMarquee({direction:'left',circular:true,scrolldelay:0,scrollamount:30,isEqual:true,runshort: false});
    }
    //群体分布数据
    function getPersonDistributionData(){
        $.ajax({
            dataType:"json",
            url:"/bigScreenController/typeDistributed",
            type:"post",
            success:function(result){
                if(result.code===10001){
                    var scaleData=[];
                    for(var i=0;i<result.data.length;i++){
                        scaleData.push({"name":result.data[i].type,"value":result.data[i].count})
                    };
                    getPersonDistribution(scaleData)
                }
            }
        })
    }
    //重点人员关注时间分布
    function getAttentionTimeData(){
        $.ajax({
            dataType:"json",
            url:"/bigScreenController/attentionTimeDistributed",
            type:"post",
            success:function(result){
                if(result.code===10001){
                    var scaleData=[],days=[];
                    for(var i=0,data=result.data;i<data.length;i++){
                        days.push(data[i].period);
                    };
                    if(days.indexOf("<3")<0){
                        result.data.push({"period":"<3","count":0})
                    }
                    if(days.indexOf("3-7")<0){
                        result.data.push({"period":"3-7","count":0})
                    }
                    if(days.indexOf("7-15")<0){
                        result.data.push({"period":"7-15","count":0})
                    }
                    if(days.indexOf("15-30")<0){
                        result.data.push({"period":"15-30","count":0})
                    }
                    if(days.indexOf(">30")<0){
                        result.data.push({"period":">30","count":0})
                    }
                    for(var i=0,data=result.data;i<data.length;i++){
                        if(data[i].period==="<3"){
                            scaleData[0]={"name":"<3","value":data[i].count}
                        }else if(data[i].period==="3-7"){
                            scaleData[1]={"name":"3-7","value":data[i].count}
                        }else if(data[i].period==="7-15"){
                            scaleData[2]={"name":"7-15","value":data[i].count}
                        }else if(data[i].period==="15-30"){
                            scaleData[3]={"name":"15-30","value":data[i].count}
                        }else{
                            scaleData[4]={"name":">30","value":data[i].count}
                        }
                    };
                    getAttentionTime(scaleData)
                }
            }
        })
    }
    //在辖区占比
    function getJurisdictionManageData(){
        $.ajax({
            dataType:"json",
            url:"/alarmStatisticsController/jurisdictionProportion",
            type:"post",
            success:function(result){
                if(result.length>0){
                    var scaleData=[];
                    var total=0;
                    for(var i=0,data=result;i<data.length;i++){
                        scaleData.push({"name":data[i].name,"value":data[i].value});
                        total+=data[i].value;
                    };
                    getJurisdictionManage(scaleData,total)
                }
            }
        })
    }
    //告警类型分布
    function getAlarmTypeData(){
        $.ajax({
            dataType:"json",
            url:"/alarmStatisticsController/findMapAlarmType",
            type:"post",
            success:function(result){
                if(result.length>0){
                    var scaleData=[];
                    for(var i=0;i<result.length;i++){
                        scaleData.push({"name":result[i].alarmName,"value":result[i].count})
                    };
                    getAlarmDistribution(scaleData)
                }
            }
        })
    }
    /*实时告警情况*/
    function getalarmTable(){
        $.ajax({
            url:"/alarmLogController/pageSelect",
            type:"post",
            data:{
                page:1,
                rows:5
            },
            dataType:"json",
            success:function(result){
                if(result.rows.length>0){
                    var html="";
                    for(var i in result.rows){
                        html+="<tr><td>"+timeFormatter(result.rows[i].alarmTime)+"</td><td>"+result.rows[i].userPhone+"</td><td>"+result.rows[i].alarmName.replace(/告警/,"")+"</td><td><div class='alarm-content'>"+result.rows[i].alarmContent+"</div></td></tr>"
                    }
                    $("#alarmContent").empty().html(html);
                    pagenation(result.total);
                }
            }
        })
    }
/*人群分布占比*/
    function getPersonDistribution(_data){
        var myChart = echarts.init(document.getElementById('personDistribution'));
        function deepCopy(obj) {
            if (typeof obj !== 'object') {
                return obj;
            }
            var newobj = {};
            for (var attr in obj) {
                newobj[attr] = obj[attr];
            }
            return newobj;
        }
        var xData = [],
            yData = [];
        var data = _data;
        for(var i in data){
            xData.push(data[i].name);
            yData.push(data[i].value);
        }
        var startColor = ['#fea42d', '#0089fa', '#da462d', '#22b18d','#cdd417'];
        var endColor = ['#0367d4', '#2743ed', '#00c4a5', '#ea2e41','#6fdfe6'];
        var borderStartColor = ['#fea42d', '#0089fa', '#da462d', '#22b18d','#cdd417'];
        var borderEndColor = ['#09c1ff', '#8171ff', '#05ffff', '#ff6584','#22b8c2'];
        var RealData = [];
        var borderData = [];
        for(var i in data){
            var newobj = deepCopy(data[i]);
            var newobj1 = deepCopy(data[i]);
            RealData.push(newobj);
            borderData.push(newobj1);
        }
        for(var i in borderData){
            borderData[i].itemStyle = {
                normal: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: borderStartColor[i] // 0% 处的颜色
                        }, {
                            offset: 1,
                            color: borderEndColor[i] // 100% 处的颜色
                        }],
                        globalCoord: false // 缺省为 false
                    }
                }
            }
        };
        option = {
            legend: {
                orient: 'vertical',
                icon:'rect',
                x: 'right',
                y:'top',
                itemGap:2,
                itemWidth:8,
                itemHeight:6,
                textStyle:{
                    color:"#fff",
                    fontSize:10
                },
                data:xData
            },
            tooltip:{
                show:true,
                formatter: function(prams) {
                    return prams.name+"："+prams.value+"人"
                }
            },
            series: [// 主要展示层的
                {
                    radius: ['44%', '70%'],
                    center: ['50%', '50%'],
                    type: 'pie',
                    label: {
                        normal: {
                            show: true,
                            //color:"#fff",
                            fontSize:12,
                            formatter: function(params) {
                                var percent = params.percent.toFixed(0);
                                if(params.name !== '') {
                                    return params.name +'\n('+percent + '%)'
                                }else {
                                    return '';
                                }
                            },
                        }
                    },
                    labelLine: {
                        normal: {
                            show: true,
                            length:10
                        }
                    },
                    color:['#fea42d', '#0089fa', '#da462d', '#22b18d','#cdd417'],
                    data: RealData,
                },
                // 边框的设置
                {
                    radius: ['40%', '44%'],
                    center: ['50%', '50%'],
                    type: 'pie',
                    label: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false
                        }
                    },
                    animation: false,
                    tooltip: {
                        show: false
                    },
                    data: borderData
                },
                // 中心的圆圈
                {
                    radius: ['35%', '40%'],
                    center: ['50%', '50%'],
                    type: 'pie',
                    label: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false
                        }
                    },
                    tooltip: {
                        show: false
                    },
                    data: [{
                        value: 100,
                        name: '',
                        itemStyle: {
                            normal: {
                                color: '#3d3d6b',
                            }
                        }
                    }],
                    animation: false
                }
            ]};
        myChart.setOption(option);
        myChart.resize()
    }
    /*重点人群关注时间*/
    function getAttentionTime(_data){
        //console.log(_data)
        var myChart = echarts.init(document.getElementById('attentionTime'));
        var xData = [],
            yData = [];
        for(var i in _data){
            xData.push(_data[i].name);
            yData.push(_data[i].value);
        }
        var max=Math.max.apply(null, yData);
        var min=Math.min.apply(null, yData);
        if(min<=10){
            min=0;
        }
        option = {
            color: ['#3398DB'],
            grid: {
                left: '0%',
                right: '0%',
                bottom: '5%',
                top: '7%',
                height: '85%',
                containLabel: true,
                z: 22
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'line',

                    lineStyle: {
                        opacity: 0
                    }
                },
                formatter: function(prams) {
                    if(prams[0].name==="长期"){
                        return "监控人数："+prams[0].data+"人</br>监控时长："+prams[0].name
                    }else{
                        return "监控人数："+prams[0].data+"</br>监控时长："+prams[0].name+"天"
                    }
                },
                fontSize:12,
            },
            xAxis: [{
                type: 'category',
                nameRotate:20,
                gridIndex: 0,
                data: xData,
                axisTick: {
                    alignWithLabel: true
                },
                axisLine: {
                    lineStyle: {
                        color: '#aaa'
                    }
                },
                axisLabel: {
                     show: true,
                     interval:0,
                     rotate:20,
                     color: 'rgb(255,255,255)',
                     fontSize:12
                }
            }],
            yAxis: [{
                    type: 'value',
                    gridIndex: 0,
                    splitLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    //min:'dataMin',
                    // max: 'dataMax',
                    axisLine: {
                        lineStyle: {
                            color: 'transparent'
                        }
                    },
                    axisLabel: {
                        color: 'rgb(255,255,255)',
                        formatter: '{value}',
                        fontSize:12
                    }
                },
                {
                    type: 'value',
                    gridIndex: 0,
                    min: min,
                    max: max,
                    splitLine: {
                        show: true,
                        lineStyle: {
                            // 使用深浅的间隔色
                            color: ['#aaa', '#ddd'],
                            width:0.5,
                            opacity:0.2
                         }
                    },
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        show: false
                    },
                    splitArea: {
                        show: true,
                        areaStyle: {
                            color: ['rgba(250,250,250,0.0)','rgba(250,250,250,0.05)']
                        }
                    }
                }
            ],
            series: [{
                    name: '合格率',
                    type: 'bar',
                    barWidth: '30%',
                    xAxisIndex: 0,
                    yAxisIndex: 0,
                    itemStyle: {
                        normal: {
                            //barBorderRadius: [30, 30, 0, 0],
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [{
                                        offset: 0,
                                        color: '#00feff'
                                    },
                                    {
                                        offset: 0.5,
                                        color: '#027eff'
                                    },
                                    {
                                        offset: 1,
                                        color: '#0286ff'
                                    }
                                ]
                            )
                        }
                    },
                    data: yData,
                    zlevel: 11
                }
            ]
        };
        myChart.setOption(option);
        myChart.resize()
    };
    /*在辖区占比*/
    function getJurisdictionManage(_data,_total){
        var myChart = echarts.init(document.getElementById('jurisdictionManage'));
        var data= _data;
        option = {
            title: {
                text: _total+'\n'+'辖区内',
                x: 'center',
                y: 'center',
                textStyle: {
                    fontWeight: 'normal',
                    fontSize:14,
                    color: "#fff",
                }
            },
            tooltip:{
                show:true,
                formatter: function(prams) {
                    return prams.name+"："+prams.value+"人"
                }
            },
            series: [
                // 主要展示层的
                {
                    radius: ['66%', '72%'],
                    center: ['50%', '50%'],
                    type: 'pie',
                    name:"人数",
                    hoverOffset:0,
                    label: {
                        normal: {
                            show: true,
                            color:"#fff",
                            fontWeight:'lighter',
                            formatter: "{b}\n{m|{c}}人",
                            rich: {//自定义样式
                                m:{
                                    fontSize:12,
                                    color:"#fff"
                                }
                            }
                        },
                        emphasis: {
                            show: true
                        },
                        textStyle: {
                            color: '#fff',
                            fontSize: 12
                        }
                    },
                    labelLine: {
                        normal: {
                            show:true,
                            length:5
                        },
                        emphasis: {
                            show: true,
                            length:5
                        }
                    },
                    animation: true,
                    color:['#547fe0','#c6177a'],
                    data:data
                },
                // 中心的圆圈
                {
                    radius: ['50%', '66%'],
                    center: ['50%', '50%'],
                    type: 'pie',
                    hoverOffset:0,
                    label: {
                        normal: {
                            show: true,
                            formatter:function(parmas){
                                return parmas.percent.toFixed(0)+"%"

                            },
                            color:"#fff",
                            fontSize:10
                        },
                        emphasis: {
                            show: true
                        }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false
                        }
                    },
                    data: [{
                        "name":data[0].name,
                        "value":data[0].value,
                        label: {
                            position: 'inside',
                            rotate: 'tangential'
                        },
                        itemStyle: {
                            normal: {
                                color: 'rgba(64,97,208,.5)'
                            }
                        }
                    }, {
                        "name": data[1].name,
                        "value":data[1].value,
                        label: {
                            position: 'inside',
                            rotate: 'tangential'
                        },
                        itemStyle: {
                            normal: {
                                color: 'rgba(164,29,110,.5)'
                            }
                        }
                    }],
                    animation: true
                },
            ]
        }
        myChart.setOption(option);
        myChart.resize()
    };
    /*告警类型分布情况*/
    function getAlarmDistribution(_data){
        var myChart = echarts.init(document.getElementById('alarmDistribution'));
        function deepCopy(obj) {
            if (typeof obj !== 'object') {
                return obj;
            }
            var newobj = {};
            for (var attr in obj) {
                newobj[attr] = obj[attr];
            }
            return newobj;
        }
        var xData = [],
            yData = [];
        var data =_data;
        for(var i in data){
            xData.push(data[i].name);
            yData.push(data[i].value);
        }
        var startColor = ['#0157be', '#7a18ed', '#00bbce', '#ea865a'];
        var endColor = ['#0367d4', '#2743ed', '#00c4a5', '#ea2e41'];
        var RealData = [];
        for (var i in data){
            var newobj = deepCopy(data[i]);
            RealData.push(newobj);
        };
        for(var i in RealData){
            RealData[i].itemStyle = {
                normal: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [{
                            offset: 0,
                            color: startColor[i] // 0% 处的颜色
                        }, {
                            offset: 1,
                            color: endColor[i] // 100% 处的颜色
                        }],
                        globalCoord: false // 缺省为 false
                    },
                }
            }
        };
        option = {
            tooltip:{
                show:true,
                formatter: function(prams) {
                    return prams.name.substring(0,4)+"："+prams.value+"人/次"
                }
            },
            series: [
                {
                    name:'',
                    type:'pie',
                    selectedMode: 'single',
                    label: {
                        normal: {
                            position: 'outside',
                            color:"#fff",
                            fontSize:12,
                            formatter:function(params){
                                var name = params.data.name
                                var newName = name.substring(0,4);
                                return newName+"\n"+"("+params.percent+"%)"
                            }
                        }
                    },
                    labelLine: {
                        normal: {
                            show: true,
                            length:3
                        }
                    },
                    data:RealData
                }
            ]
        };
        myChart.setOption(option);
        myChart.resize();
        myChart.on("pieselectchanged",function(params){
            var flag=[],html="";
            $.each(params.selected, function(idx, obj) {
                flag.push(obj);
            });
            if(flag.indexOf(true)<0){//没有选中的扇形
                $.ajax({
                    url:"/alarmLogController/pageSelect",
                    type:"post",
                    data:{page:1,rows:5},
                    dataType:"json",
                    success:function(result){
                        if(result.rows.length>0){
                            for(var i in result.rows){
                                html+="<tr><td>"+timeFormatter(result.rows[i].alarmTime)+"</td><td>"+result.rows[i].userPhone+"</td><td>"+result.rows[i].alarmName.replace(/告警/,"")+"</td><td class='content'><p class='alarm-content'>"+result.rows[i].alarmContent+"</p></td></tr>"
                            }
                            $("#alarmContent").empty().html(html);
                            pagenation(result.total);
                        }
                    }
                })
            }else{//选中的扇形
                $.ajax({
                    url:"/alarmStatisticsController/findByType",
                    type:"post",
                    data:{page:1, rows:5,index:params.name.substring(4)},
                    dataType:"json",
                    success:function(result){
                        if(result.rows.length>0){
                            for(var i in result.rows){
                                html+="<tr><td>"+timeFormatter(result.rows[i].alarmTime)+"</td><td>"+result.rows[i].userPhone+"</td><td>"+result.rows[i].alarmName.replace(/告警/,"")+"</td><td><p class='alarm-content'>"+result.rows[i].alarmContent+"</p></td></tr>"
                            }
                            $("#alarmContent").empty().html(html);
                            pagenation(result.total);
                        }
                    }
                })
            }
        })
    };
    // 市值变化时 处理区/县
    function doCityAndCountyRelation(cityJson,city,county) {
        var cityVal = city.select2('val').split(',')[0];
        var sb = new StringBuffer();
        $.each(cityJson,function(i, val) {
            if (cityVal == val.name ) {
                for(var j=0,area=val.children;j<area.length;j++){
                    sb.append("<option value='"+area[j]+"'>"+area[j] +"</option>");
                }
            }else if(cityVal == ''){
                sb.append("<option value='全部'>全部</option>");
                return false
            }
        });
        county.empty().html(sb.toString());
        county.select2({minimumResultsForSearch: -1});
    };
    function StringBuffer(str) {
        var arr = [],str = str || "",size = 0;// 存放数组大小
        arr.push(str);
        // 追加字符串
        this.append = function(str1) {arr.push(str1);return this;};
        // 返回字符串
        this.toString = function() {return arr.join("");};
        // 清空
        this.clear = function(key) {size = 0;arr = [];};
        // 返回数组大小
        this.size = function() {return size;};
        // 返回数组
        this.toArray = function() {return buffer;};
        // 倒序返回字符串
        this.doReverse = function() {var str = buffer.join('');str = str.split('');return str.reverse().join('');};
    }
})